import React, { useState, useEffect } from 'react'
import { Form, Input, InputNumber, Switch, Button, Upload, TreeSelect, message, MessageArgsProps, Image } from 'antd'
import { getCates } from '@/api/cate'
import { addItem } from '@/api/item'
import { useNavigate } from 'react-router-dom'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-react'


export default function ItemAdd() {
    const navigate = useNavigate()

    // 表格完成 提交
    const submitAddItem = (params = {}) => {
        addItem({
            ...params,
            thumb,
            content: html
        }).then(res => {
            if (res.data.code === 200) {
                message.success(res.data.msg, 1.5, () => {
                    // 新增完成 跳转回 商品列表
                    navigate('/itemLists', { replace: true })
                })
            }
        })
    }

    // 图片上传成功 回调提示
    const [thumb, setThumb] = useState('')
    const uploadStateChange = (info: any) => {
        // info 状态为 完成
        if (info.file.status === 'done') {
            // 图片
            if (info.file.response.code === 200) {
                setThumb(info.file.response.data.url)
                message.success('图片上传成功', 1.5, () => { })
            }
        }
    }

    // 获取分类列表 赋值
    const [cates, setCates] = useState([])
    const fetchCates = () => {
        getCates().then(res => {
            if (res.data.code === 200) {
                setCates(res.data.data)
            }
        })
    }

    useEffect(() => { fetchCates() }, [])

    // 富文本编辑器
    // editor 实例
    const [editor, setEditor] = useState(null)

    // 编辑器内容
    const [html, setHtml] = useState('<p>hello</p>')

    // 编辑器配置
    const editorConfig = {
        placeholder: '请输入内容...',
        // 针对设置图片 不能使用的问题
        // 官网 配置和 API----菜单配置
        MENU_CONF: {
            uploadImage: {
                // 注意mock接口设置
                server: '/api/upload',
                // 自定义
                customInsert(res:any, insertPic:any){
                    insertPic(res.data.url)
                }
            }
        }

    }

    // 工具栏配置
    const toolbarConfig = {}

    // 及时销毁 editor ，重要！
    useEffect(() => {
        return () => {
            if (editor == null) return
            editor.destroy()
            setEditor(null)
        }
    }, [editor])

    return (
        <Form
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 800 }}
            initialValues={{ onsale: true }}
            onFinish={submitAddItem}
            autoComplete="off"
        >
            <Form.Item
                label="商品名"
                name="itemName"
                rules={[{ required: true, message: '商品名必填！' }]}
            >
                <Input />
            </Form.Item>

            <Form.Item
                label="商品价格"
                name="price"
                rules={[{ required: true, message: '价格必填！' }]}
            >
                <InputNumber min={0} />
            </Form.Item>

            <Form.Item
                label="上下架"
                name="onsale"
                valuePropName='checked'
                rules={[
                    { required: true, message: '必须选择!' }
                ]}
            >
                <Switch checkedChildren="上架" unCheckedChildren="下架" />
            </Form.Item>

            <Form.Item
                label="商品分类"
                name="cateId"
                valuePropName='checked'
                rules={[{ required: true, message: '分类必填！' }]}
            // wrapperCol={{ offset: 8, span: 16 }}
            >
                <TreeSelect
                    showSearch
                    style={{ width: '100%' }}
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                    placeholder="选择商品分类"
                    allowClear
                    treeDefaultExpandAll
                    // 接收父组件数据 渲染到子组件
                    treeData={cates}
                    fieldNames={
                        {
                            label: 'cateName',
                            value: 'id',
                            children: 'children'
                        }
                    }
                />
            </Form.Item>

            <Form.Item
                label="分类图标"
                name="cateIcon"
            >
                <Upload
                    name='file'
                    action="/api/upload"
                    accept='.gif, .png, .jpg'
                    onChange={
                        uploadStateChange
                    }
                >
                    <Button>点击上传</Button>
                </Upload>
                <Image width={thumb ? 100 : 0} src={thumb} />

            </Form.Item>

            <Form.Item
                label="商品描述"
                name="desc"
            >
                <Input.TextArea />
            </Form.Item>

            <Form.Item label="富文本编辑器">

                <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
                    <Toolbar
                        editor={editor}
                        defaultConfig={toolbarConfig}
                        mode="default"
                        style={{ borderBottom: '1px solid #ccc' }}
                    />
                    <Editor
                        defaultConfig={editorConfig}
                        value={html}
                        onCreated={setEditor}
                        onChange={editor => setHtml(editor.getHtml())}
                        mode="default"
                        style={{ height: '500px', overflowY: 'hidden' }}
                    />
                </div>
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="primary" htmlType="submit">
                    确定新增
                </Button>
            </Form.Item>
        </Form>
    )
}
